<template>
  <div class="news-container">
    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>新闻公告管理</span>
          <el-button type="primary" @click="showAddNewsDialog">发布新闻公告</el-button>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter-section">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="标题">
            <el-input 
              v-model="searchForm.标题" 
              placeholder="请输入标题"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="类型">
            <el-select 
              v-model="searchForm.类型" 
              placeholder="请选择类型"
              clearable
            >
              <el-option label="新闻" value="新闻"></el-option>
              <el-option label="公告" value="公告"></el-option>
              <el-option label="活动" value="活动"></el-option>
              <el-option label="其他" value="其他"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布时间范围">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <el-table 
        v-loading="loading" 
        :data="paginatedNews" 
        style="width: 100%"
        border
      >
        <el-table-column prop="公告ID" label="新闻ID" width="100" />
        <el-table-column prop="公告标题" label="标题" min-width="250">
          <template #default="{ row }">
            <span class="news-title" @click="viewNewsDetail(row.公告ID)">{{ row.公告标题 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100">
          <template #default="{ row }">
            {{ row.类型 || '新闻' }}
          </template>
        </el-table-column>
        <el-table-column label="发布人" width="120">
          <template #default="{ row }">
            {{ getPublisherName(row.创建用户ID) }}
          </template>
        </el-table-column>
        <el-table-column prop="发布时间" label="发布时间" width="180" />
        <el-table-column prop="浏览量" label="浏览量" width="100">
          <template #default="{ row }">
            <el-tag size="small" effect="plain">{{ row.浏览量 || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="状态" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="row.状态 === '发布' ? 'success' : 'draft'" 
              effect="plain"
            >
              {{ row.状态 === '发布' ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="viewNewsDetail(row.新闻ID)">查看</el-button>
            <el-button type="primary" size="small" @click="editNews(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteNews(row.新闻ID)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredNews.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑新闻公告对话框 -->
    <el-dialog
      v-model="newsDialogVisible"
      :title="dialogType === 'add' ? '发布新闻公告' : '编辑新闻公告'"
      width="800px"
      destroy-on-close
    >
      <el-form 
        :model="newsForm" 
        ref="newsFormRef" 
        label-width="120px"
        :rules="formRules"
      >
        <el-form-item label="标题" prop="标题">
          <el-input 
            v-model="newsForm.标题" 
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="类型">
          <el-select v-model="newsForm.类型" placeholder="请选择类型">
            <el-option label="新闻" value="新闻"></el-option>
            <el-option label="公告" value="公告"></el-option>
            <el-option label="活动" value="活动"></el-option>
            <el-option label="其他" value="其他"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="摘要" prop="摘要">
          <el-input 
            v-model="newsForm.摘要" 
            placeholder="请输入内容摘要"
            type="textarea"
            rows="2"
          ></el-input>
        </el-form-item>
        <el-form-item label="封面图片">
          <el-upload
            class="upload-demo"
            drag
            action="#"
            :on-change="handleImageChange"
            :auto-upload="false"
            :limit="1"
            accept="image/*"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              <em>点击或拖拽图片到此处上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              支持 JPG、PNG、GIF 格式图片，建议尺寸 800x400
            </div>
          </el-upload>
          <div v-if="newsForm.封面图片" class="image-preview">
            <el-image :src="newsForm.封面图片" fit="cover" style="width: 200px; height: 100px;"></el-image>
          </div>
        </el-form-item>
        <el-form-item label="内容" prop="内容">
          <div class="editor-container">
            <!-- 简化版编辑器，实际项目中可以使用富文本编辑器 -->
            <el-input 
              v-model="newsForm.内容" 
              placeholder="请输入详细内容"
              type="textarea"
              rows="10"
            ></el-input>
          </div>
        </el-form-item>
        <el-form-item label="发布人" prop="发布人">
          <el-input 
            v-model="newsForm.发布人" 
            placeholder="请输入发布人姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="发布时间" prop="发布时间">
          <el-date-picker
            v-model="newsForm.发布时间"
            type="datetime"
            placeholder="选择发布时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="状态">
          <el-radio-group v-model="newsForm.状态">
            <el-radio value="draft">草稿</el-radio>
            <el-radio value="发布">发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="备注">
          <el-input 
            v-model="newsForm.备注" 
            placeholder="请输入备注信息"
            type="textarea"
            rows="2"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="newsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitNewsForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { newsAPI, userAPI } from '../api'

// 状态数据
const loading = ref(false)
const news = ref([])
const users = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const searchForm = ref({
  标题: '',
  类型: ''
})
const dateRange = ref([])

// 对话框相关
const newsDialogVisible = ref(false)
const dialogType = ref('add')
const newsFormRef = ref()
const newsForm = ref({
  新闻ID: '',
  标题: '',
  类型: '',
  摘要: '',
  封面图片: '',
  内容: '',
  发布人: '',
  发布时间: '',
  浏览量: 0,
  状态: 'draft',
  备注: ''
})

// 表单验证规则
const formRules = {
  标题: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { min: 2, max: 200, message: '标题长度应在 2 到 200 个字符之间', trigger: 'blur' }
  ],
  类型: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  摘要: [
    { required: true, message: '请输入摘要', trigger: 'blur' },
    { max: 500, message: '摘要长度不能超过 500 个字符', trigger: 'blur' }
  ],
  内容: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ],
  发布人: [
    { required: true, message: '请输入发布人', trigger: 'blur' }
  ],
  发布时间: [
    { required: true, message: '请选择发布时间', trigger: 'change' }
  ]
}

// 根据搜索条件过滤新闻公告
const filteredNews = computed(() => {
  let result = news.value
  
  // 根据标题过滤
  if (searchForm.value.标题) {
    const title = searchForm.value.标题
    result = result.filter(item => item.公告标题?.includes(title))
  }
  
  // 根据类型过滤
  if (searchForm.value.类型) {
    result = result.filter(item => item.类型 === searchForm.value.类型)
  }
  
  // 根据日期范围过滤
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = new Date(dateRange.value[0])
    const endDate = new Date(dateRange.value[1])
    endDate.setHours(23, 59, 59, 999)
    
    result = result.filter(item => {
      const publishDate = new Date(item.发布时间)
      return publishDate >= startDate && publishDate <= endDate
    })
  }
  
  return result
})

// 分页新闻公告
const paginatedNews = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredNews.value.slice(start, end)
})

// 获取数据
const getData = async () => {
  loading.value = true
  try {
    // 并发获取新闻公告列表和用户列表
    const [newsData, usersData] = await Promise.all([
      newsAPI.getNews(),
      userAPI.getUsers()
    ])
    news.value = newsData
    users.value = usersData
  } catch (error) {
    ElMessage.error('获取数据失败')
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取发布人姓名
const getPublisherName = (userId) => {
  if (!userId) return '未知'
  const user = users.value.find(u => u.用户ID === userId)
  return user ? user.姓名 : '未知用户'}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    标题: '',
    类型: ''
  }
  dateRange.value = []
  currentPage.value = 1
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 图片上传处理
const handleImageChange = (file, fileList) => {
  if (fileList.length > 0) {
    // 由于是模拟环境，这里仅使用base64预览
    const reader = new FileReader()
    reader.onload = (e) => {
      newsForm.value.封面图片 = e.target.result
    }
    reader.readAsDataURL(file.raw)
  }
}

// 显示添加新闻公告对话框
const showAddNewsDialog = () => {
  dialogType.value = 'add'
  newsForm.value = {
    新闻ID: '',
    标题: '',
    类型: '',
    摘要: '',
    封面图片: '',
    内容: '',
    发布人: '',
    发布时间: new Date().toISOString(),
    浏览量: 0,
    状态: 'draft',
    备注: ''
  }
  newsDialogVisible.value = true
}

// 编辑新闻公告
const editNews = (row) => {
  dialogType.value = 'edit'
  newsForm.value = {
    新闻ID: row.公告ID,
    标题: row.公告标题,
    类型: row.类型 || '新闻',
    摘要: '',
    封面图片: '',
    内容: row.公告内容 || '',
    发布人: getPublisherName(row.创建用户ID),
    发布时间: row.发布时间,
    浏览量: row.浏览量 || 0,
    状态: row.状态 || '发布',
    备注: ''
  }
  newsDialogVisible.value = true
}

// 提交表单
const submitNewsForm = async () => {
  try {
    await newsFormRef.value.validate()
    
    if (dialogType.value === 'add') {
      // 生成新闻ID
      const newNews = {
        ...newsForm.value,
        新闻ID: Date.now(), // 简单生成ID
        创建时间: new Date().toISOString(),
        浏览量: 0
      }
      
      await newsAPI.addNews(newNews)
      ElMessage.success('新闻公告发布成功')
    } else {
      const updatedNews = {
        ...newsForm.value,
        更新时间: new Date().toISOString()
      }
      await newsAPI.updateNews(updatedNews)
      ElMessage.success('新闻公告更新成功')
    }
    
    newsDialogVisible.value = false
    getData() // 重新获取数据
  } catch (error) {
    if (error !== false) { // 非表单验证错误
      ElMessage.error('操作失败，请重试')
      console.error('操作失败:', error)
    }
  }
}

// 删除新闻公告
const deleteNews = async (newsId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该新闻公告吗？此操作不可撤销！',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await newsAPI.deleteNews(newsId)
    ElMessage.success('新闻公告已删除')
    getData() // 重新获取数据
  } catch (error) {
    if (error !== 'cancel' && error !== 'close') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

// 查看新闻公告详情
const viewNewsDetail = async (newsId) => {
  try {
    // 获取新闻详情
    const newsItem = news.value.find(item => item.公告ID === newsId)
    if (newsItem) {
      // 更新浏览量
      const updatedNews = {
        ...newsItem,
        浏览量: (newsItem.浏览量 || 0) + 1
      }
      await newsAPI.updateNews(updatedNews) 
      
      // 这里可以实现跳转到详情页面或显示详情对话框
      ElMessage.success('查看详情功能待实现')
      getData() // 重新获取数据以更新浏览量
    }
  } catch (error) {
    ElMessage.error('查看失败')
    console.error('查看失败:', error)
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getData()
})
</script>

<style scoped>
.news-container {
  padding: 20px;
  background-color: #FFFFFF;
  min-height: calc(100vh - 100px);
  border: 1px solid #e0e0e0;
}

.page-card {
  margin-bottom: 20px;
  border-color: #e0e0e0;
  background-color: #FFFFFF;
  box-shadow: none;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #000000;
}

/* 确保标题文字为黑色 */
.card-header span {
  color: #000000 !important;
}

.search-filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #FFFFFF;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  box-shadow: none;
}

.search-form {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.news-title {
  color: #409eff;
  cursor: pointer;
  text-decoration: underline;
}

.news-title:hover {
  color: #66b1ff;
}

.editor-container {
  min-height: 200px;
}

.image-preview {
  margin-top: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-form .el-form-item {
    margin-bottom: 15px;
  }
}

/* 适配Element Plus主题下的组件 */
:deep(.el-input__wrapper),
:deep(.el-select__wrapper),
:deep(.el-date-editor .el-input__wrapper) {
  background-color: #FFFFFF !important;
  border-color: #dcdfe6 !important;
  color: #000000;
}

:deep(.el-input__placeholder),
:deep(.el-select__placeholder) {
  color: #c0c4cc !important;
}

:deep(.el-input__inner),
:deep(.el-select__input) {
  color: #000000 !important;
}

/* 表格样式 */
:deep(.el-table) {
  background-color: #FFFFFF;
  color: #000000;
}

:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #000000;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__row) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}

:deep(.el-button--default) {
  background-color: #ffffff;
  border-color: #dcdfe6;
  color: #606266;
}

:deep(.el-button--default:hover) {
  background-color: #f5f7fa;
  border-color: #c0c4cc;
  color: #409eff;
}

/* 对话框样式 */
:deep(.el-dialog__wrapper .el-dialog) {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
}

:deep(.el-dialog__wrapper .el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  background-color: #ffffff;
}

:deep(.el-dialog__wrapper .el-dialog__title) {
  color: #000000;
}

:deep(.el-dialog__wrapper .el-form-item__label) {
  color: #000000;
}

:deep(.el-dialog__body) {
  background-color: #ffffff;
}

:deep(.el-dialog__footer) {
  background-color: #ffffff;
  border-top: 1px solid #ebeef5;
}

/* 上传组件样式 */
:deep(.el-upload-dragger) {
  background-color: #fafafa;
  border: 2px dashed #dcdfe6;
  color: #000000;
}
</style>